/**   
 * @Title: PictureCheckCode.java
 * @Package cn.iyizhan.treamwork.servlet.manager
 * @Description: TODO(用一句话描述该文件做什么)
 * @author buyuer
 * @date 2015年11月7日 上午10:48:39 
 * @version V1.0
 */
package cn.pegasus.teamwork.manager.servlet;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.iyizhan.teamwork.base.util.IdentifyingCode;

/**
 * @ClassName: PictureCheckCode
 * @Description: 图片验证码servlet
 * @author buyuer
 * @date 2015年11月7日 上午10:48:39
 * 
 */

@SuppressWarnings("serial")
public class PictureCheckCode extends HttpServlet {

    public PictureCheckCode() {
        super();
    }

    public void init() throws ServletException {
        super.init();
    }

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置不缓存图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        // 指定生成的相应图片
        response.setContentType("image/jpeg");
        IdentifyingCode idCode = new IdentifyingCode();
        BufferedImage image = new BufferedImage(idCode.getWidth(), idCode.getHeight(), BufferedImage.TYPE_INT_BGR);
        Graphics2D g = image.createGraphics();
        // 定义字体样式
        Font myFont = new Font("黑体", Font.BOLD, 17);
        // 设置字体
        g.setFont(myFont);

        g.setColor(idCode.getRandomColor(200, 250));
        // 绘制背景
        g.fillRect(0, 0, idCode.getWidth(), idCode.getHeight());

        g.setColor(idCode.getRandomColor(180, 200));
        idCode.drawRandomLines(g, 160);
        String code = idCode.drawRandomString(4, g);
        //装载code 到session中
        request.getSession().setAttribute("code", code);
        g.dispose(); 
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
